package com.tmeone.erpone.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tmeone.erpone.entity.*;
import com.tmeone.erpone.service.*;
import com.tmeone.erpone.util.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tmeone
 * @since 2021-04-19
 */
@RestController
public class TOrderController {

    @Autowired
    private ITOrderService orderService;
    @Autowired
    private ITProductService productService;
    @Autowired
    private ITCategoriesService categoriesService;
    @Autowired
    private ISCompanyService companyService;
    @Autowired
    private ITOrderStatusService orderStatusService;
    @Autowired
    private ITProductionLineService productionLineService;
    @Autowired
    private TReviewService reviewService;
    @Autowired
    private ISUserService userService;
    @Autowired
    private MyUser myUser;

    //分页,状态,模糊综合查询
    @GetMapping("/orders-all")
    public JsonResult getPageAll(String orderState,String orderId,String dealTime,
                                 @RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
                                 @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize){
        IPage<TOrder> page = new Page<>(current,pageSize);
        IPage<TOrder> orderIPage = orderService.getPageAll(page,orderState,orderId,dealTime);
        for (TOrder record : orderIPage.getRecords()) {
            //商品
            TProduct tProduct = productService.getOne(new QueryWrapper<TProduct>().lambda().eq(TProduct::getId, record.getProductId()));
            if (tProduct != null){
                //商品类型
                TCategories tCategories = categoriesService.getOne(new QueryWrapper<TCategories>().lambda().eq(TCategories::getId, tProduct.getPEnterprise()));
                if (tCategories != null){
                    tProduct.setPEnterprise(tCategories.getName());
                }
                record.setProduct(tProduct);
            }
            //企业
            SCompany sCompany = companyService.getOne(new QueryWrapper<SCompany>().lambda().eq(SCompany::getId, record.getCustomId()));
            if (sCompany != null){
                record.setCompany(sCompany);
            }

            //订单状态
            TOrderStatus orderStatus1 = orderStatusService.getOne(new QueryWrapper<TOrderStatus>().lambda().eq(TOrderStatus::getId, record.getOrderStatus()));
            if (orderStatus1 != null){
                record.setT_orderStatus(orderStatus1);
            }
        }
        return new JsonResult(1,orderIPage);

    }

    //添加订单
    @PostMapping("/order")
    public JsonResult addOrder(@RequestBody TOrder order){
        order.setId(Long.toString(new Date().getTime()));
        order.setOrderId(Long.toString(new Date().getTime()));
        orderService.save(order);
        return new JsonResult(1,null);
    }

    //订单排单分页
    @GetMapping("/orders2")
    public JsonResult getPage2(String list,
                               @RequestParam(value = "current",required = false,defaultValue = "1") Integer current,
                              @RequestParam(value = "pageSize",required = false,defaultValue = "5") Integer pageSize){
        IPage<TOrder> page = new Page<>(current,pageSize);
        IPage<TOrder> orderIPage = orderService.getSortPage(page,list);
        for (TOrder record : orderIPage.getRecords()) {
            //商品
            TProduct tProduct = productService.getOne(new QueryWrapper<TProduct>().lambda().eq(TProduct::getId, record.getProductId()));
            if (tProduct != null){
                //商品类型
                TCategories tCategories = categoriesService.getOne(new QueryWrapper<TCategories>().lambda().eq(TCategories::getId, tProduct.getPEnterprise()));
                if (tCategories != null){
                    tProduct.setPEnterprise(tCategories.getName());
                }
                record.setProduct(tProduct);
            }
            //订单状态
            TOrderStatus orderStatus = orderStatusService.getOne(new QueryWrapper<TOrderStatus>().lambda().eq(TOrderStatus::getId, record.getProductStatus()));
            if (orderStatus != null){
                record.setT_orderStatus(orderStatus);
            }
            //产能
            TProductionLine productionLine = productionLineService.getOne(new QueryWrapper<TProductionLine>().lambda().eq(TProductionLine::getId, record.getProductLineId()));
            if (productionLine != null){
                record.setProductionLine(productionLine);
            }
        }
        return new JsonResult(1,orderIPage);
    }

    //修改订单
    @PutMapping("/order-list")
    public JsonResult updOrder(@RequestBody TOrder order){
        orderService.updOrder(order);
        return new JsonResult(1,null);
    }

    /**
     * 分页查询所有订单
     * 可选条件查询，参数为null为非条件查询
     * 作者：wzs
     * @param current 当前页数
     * @param pageSize 每页行数
     * @param orderType 订单类型
     * @param orderStatus 订单状态
     * @param orderId 订单id
     * @param dealTime 交易时间
     * @return 所有订单
     */
    public JsonResult orders(@RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
                             @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                             @RequestParam(value = "orderType", required = false) String orderType,
                             @RequestParam(value = "orderStatus", required = false) String orderStatus,
                             @RequestParam(value = "orderId", required = false) String orderId,
                             @RequestParam(value = "dealTime", required = false) String dealTime) {


        Page<TOrder> page = new Page<>(current, pageSize);
        return new JsonResult(1,orderService.selectAllByOrderTypeAndOrderStatusAndOrderIdLikeAndDealTime(page,orderType,orderStatus,orderId,dealTime));
    }

    /**
     * 分页查询所有采购订单
     * 可选条件查询，参数为null为非条件查询
     * 作者：wzs
     * @param current 当前页数
     * @param pageSize 每页行数
     * @param orderStatus 订单状态
     * @param orderId 订单id
     * @param dealTime 交易时间
     * @return 所有订单
     */
    @GetMapping("/PurchaseOrders")
    public JsonResult purchaseOrders(@RequestParam(value = "current", required = false, defaultValue = "1") Integer current,
                                     @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize,
                                     @RequestParam(value = "orderStatus", required = false) String orderStatus,
                                     @RequestParam(value = "orderId", required = false) String orderId,
                                     @RequestParam(value = "dealTime", required = false) String dealTime) {
        JsonResult jsonResult = orders(current, pageSize, "采购订单", orderStatus, orderId, dealTime);
        for (TOrder order :  ((Page<TOrder>) jsonResult.getData()).getRecords()) {
            TReview review = reviewService.getOne(new QueryWrapper<TReview>().lambda().eq(TReview::getOrderNumber, order.getOrderId()));
            if (review != null) {
                review.setUser(userService.getById(review.getReview()));
                order.setReview(review);
            }
        }
        return jsonResult;
    }


    /**
     * 批量添加采购订单
     * 作者：wzs
     * @param purchaseOrders 采购订单
     * @return 响应信息
     */
    @PostMapping("/PurchaseOrders")
    public JsonResult addPurchaseOrders(@RequestBody List<TOrder> purchaseOrders) {
        // 获取当前用户
        SUser user = myUser.getUser();

        List<TReview> reviews = new ArrayList<>();
        for (TOrder purchaseOrder : purchaseOrders) {
            // 查询当前商品
            TProduct product = productService.getById(purchaseOrder.getProductId());

            // 生成随机id
            purchaseOrder.setId(UUID.randomUUID().toString().replace("-", "").substring(0, 10));
            // 设置下单用户
            purchaseOrder.setOrderHolder(user.getId());
            // 设置订单类型为采购订单
            purchaseOrder.setOrderType("采购订单");
            // 计算总价
            purchaseOrder.setMoney(purchaseOrder.getNumber() * product.getPPrice());
            // 设置订单下单公司id
            purchaseOrder.setCustomId(user.getCompanyId());
            // 设置订单供应商id
            purchaseOrder.setSupplierId(product.getCompanyId());

            // 审核表
            TReview review = new TReview();
            review.setOrderNumber(purchaseOrder.getOrderId());
            review.setDepartmentId(Integer.valueOf(user.getDId()));
            review.setReviewStatus("待审核");
            reviews.add(review);
        }
        if (orderService.saveBatch(purchaseOrders)) {
            reviewService.saveBatch(reviews);
        }
        return new JsonResult(1, null);
    }

    /**
     * 批量审核
     * 作者：wzs
     * @param reviews 审核信息
     * @return JsonResult
     */
    @PutMapping("/reviews")
    public JsonResult reviews(@RequestBody List<TReview> reviews) {
        for (TReview review : reviews) {
            review.setReview(myUser.getUser().getId());
        }
        reviewService.updateBatchById(reviews);
        return new JsonResult(1,null);
    }
    @Autowired
    private ITOrderService itOrderService;
    @ResponseBody
    @RequestMapping("/t-order")
    public JsonResult selectListOrderGo(@RequestParam(value = "current", required = false, defaultValue = "1") Integer current) {
        try {
            IPage<TOrder> arg = new Page<>(current, 5);
            IPage<TOrder> page = itOrderService.pageTOrderGo(arg);
            return new JsonResult(1, page);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    @RequestMapping(value = "/orderById/{orderId}", method = RequestMethod.GET)
    public JsonResult selectOrderByOrderId(@PathVariable String orderId){
        return new JsonResult(1,itOrderService.selectOrderByOrderId(orderId));
    }
}
